package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.user.property.IPropertyUserServiceClient;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <desc>
 *      物业登录拦截器
 * </desc>
 *
 * @createDate 2017/10/17
 */
@Aspect
@Component
public class PropertyLoginInterceptor {

    //拦截点
    @Pointcut("execution(* com.itlong.cloud.controller..*.*(..)) && !@annotation(com.itlong.cloud.annotation.UnAuthAccessRequired)")
    public void excudeService(){}

    //需要排除拦截的方法
    @Value("${"+ PlatformConstants.PROPERTY_USER_TOKEN_DONTINTERCEPT+"}")
    String dontIntercept;

    //物业拦截模式
    @Value("${"+ PlatformConstants.PROPERTY_LOGIN_INTECEPT_MODE+"}")
    String inteceptMode;

    @Autowired
    IPropertyUserServiceClient iPropertyUserServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    /**
     * <desc>
     *      在切面处excudeService 做拦截处理 为了防止拦截后token失效 采用Around
     * <desc/>
     * @param
     * @return
     * @author Biao.R
     * @createDate 2017/10/17
     */
   @Around("excudeService()")
   public Object propertyInterceptor(ProceedingJoinPoint thisJoinPoint) throws Throwable {
       if (!"devTest".equals(inteceptMode.trim())) {
           HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                /*String uri = request.getRequestURI();
                if (uri.indexOf("error") > -1 || uri.indexOf("404") > -1) {
                    return thisJoinPoint.proceed();
                }*/
           //获取目标方法全路径
           String methodName = thisJoinPoint.getSignature().getName();
           String[] notInterceptMethods = StringHandlerUtil.splitString(dontIntercept);
           //循环配置不需要拦截的方法
           for (String method : notInterceptMethods) {
               method = method.replaceAll("\\*", "");
               if (methodName.contains(method)) {
                   return thisJoinPoint.proceed();
               }
           }

           String loginUserId = request.getParameter("loginUserId");
           if (loginUserId == null) {
               loginUserId = request.getAttribute("loginUserId") == null ? null : request.getAttribute("loginUserId").toString();
           }
           String token = request.getParameter("token");
           if (token == null) {
               token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
           }

           String projectId = request.getParameter("projectId");
           if (projectId == null) {
               projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
           }
           if(StringUtils.isNotEmpty(projectId)){
               if(iOperateProjectServiceClient.getProjectStatus(projectId) == 2){
                   return new MessageVO(PropertyErrorCodeEnum.PUB_CHECK_TOKEN_FAIL.getErrorCode());
               }
           }

           if (StringUtils.isBlank(loginUserId) || StringUtils.isBlank(token)) {
               return new MessageVO(PropertyErrorCodeEnum.PUB_LOGIN_PARAMS_IS_EMPTY.getErrorCode());
           }
           // 测试拦截效果，后期去掉
           //System.out.println("物业拦截器：" + DateUtil.getCurrentTime() + "-IP-" + request.getRemoteAddr() + "-loginUserId-" + loginUserId + "-token-" + token + "-uri-" + request.getRequestURI());
           //校验token
           PropertyUserCacheVO cacheUser = iPropertyUserServiceClient.checkCacheUser(loginUserId, token);
           if (cacheUser == null) {
//               return new MessageVO(PropertyErrorCodeEnum.PUB_CHECK_TOKEN_FAIL.getErrorCode());
               return new MessageVO(PropertyErrorCodeEnum.PUB_ACCOUNT_REMOTE_LOGIN.getErrorCode());
           }else {
               if(StringUtils.isNotEmpty(String.valueOf(cacheUser.getIsLongTimeNoOperation())) && cacheUser.getIsLongTimeNoOperation()){
                   return new MessageVO(PropertyErrorCodeEnum.PUB_CHECK_TOKEN_FAIL.getErrorCode());
               }else{
                   return thisJoinPoint.proceed();
               }
           }
       } else {
           return thisJoinPoint.proceed();
       }
   }


}